<template>
	<div class="register" id="register-index">
		<div class="box-card" v-if="false">
			<div class="register-title">用户注册</div>
			<div class="register-account">
				<el-form :model="registerForm" :rules="registerRules" ref="registerRef" label-width="80px" label-position="right" show-message>
					<el-form-item label="用户名" prop="username"><el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input></el-form-item>
					<el-form-item label="密码" prop="password"><el-input v-model="registerForm.password" placeholder="请输入密码" type="password"></el-input></el-form-item>
					<el-form-item label="确认密码" prop="checkPass">
						<el-input v-model="registerForm.checkPass" placeholder="请输入确认密码" type="password"></el-input>
					</el-form-item>
					<el-form-item label="验证码" prop="code">
						<el-input v-model="registerForm.code" placeholder="请输入验证码" maxlength="4">
							<template slot="append">
								<img :src="captcha.img" mode class="captcha" @click="getCode" />
							</template>
						</el-input>
					</el-form-item>
				</el-form>
				<div class="xy" @click="check">
					<div class="xy-wrap">
						<div class="iconfont" :class="ischecked ? 'iconxuanze-duoxuan' : 'iconxuanze'"></div>
						<div class="content">
							阅读并同意
							<b @click.stop="getAggrement">《服务协议》</b>
						</div>
					</div>
					<div class="toLogin" @click="toLogin">已有账号，立即登录</div>
				</div>
				<el-button @click="register">立即注册</el-button>
			</div>
			<el-dialog :title="agreement.title" :visible.sync="aggrementVisible" width="60%" :before-close="aggrementClose" :lock-scroll="false" center>
				<div v-html="agreement.content" class="xyContent"></div>
			</el-dialog>
		</div>

		<div class="content-register">
			<div class="header-reg">
				<div class="reg-tab">
					<div :class="['tab',tabIndex == 1?'tab-act':'']" @click="setTab(1)">{{ $t('auth.register.mobile') }}</div>
					<div :class="['tab',tabIndex == 2?'tab-act':'']" @click="setTab(2)">{{ $t('auth.register.email') }}</div>
				</div>
			</div>
			<div class="form-box">
				<el-form :model="formObj" :rules="formRules"  ref="formRef" label-width="90px" label-position="right">
					<el-form-item :label="$t('auth.register.name')" prop="nickname">
						<div class="apply-wrap">
							<el-input v-model="formObj.nickname" :placeholder="$t('auth.register.iname') "></el-input>
						</div>
					</el-form-item>
					<el-form-item :label="$t('auth.register.mobile')"  v-show="tabIndex == 1">
						<div class="row-box">
							<div class="apply-wrap">
								<div class="code" @click="showTel = !showTel">
									<span>+{{formObj.phone_code}}</span>
									<i class="el-icon-arrow-up" v-show="showTel" style="color:#ccc;"></i>
									<i class="el-icon-arrow-down" v-show="!showTel" style="color:#ccc;"></i>
								</div>
								<el-input v-model="formObj.mobile" :placeholder="$t('auth.register.imobile')"></el-input>
							</div>
							<transition name="el-fade-in-linear">
								<div class="country-ul" v-show="showTel">
									<div class="country-li" v-for="(obj,i) in countryAry" :key="i" @click.stop="setCountry(obj)">
										<div class="li-name">{{obj.name}}  <span style="color: #92969E;">+{{obj.tel}}</span></div>
									</div>
								</div>
							</transition>
						</div>
					</el-form-item>
					<el-form-item :label="$t('auth.register.email')"  v-show="tabIndex == 2">
						<div class="apply-wrap">
							<el-input v-model="formObj.email" :placeholder="$t('auth.register.iemail')"></el-input>
						</div>
					</el-form-item>
					<el-form-item :label="$t('auth.register.password')" prop="password">
						<div class="apply-wrap">
							<el-input type="password" v-model="formObj.password" :placeholder="$t('auth.register.ipassword')"></el-input>
						</div>
					</el-form-item>
					<el-form-item :label="$t('auth.register.transactionPassword')" prop="pay_password">
						<div class="apply-wrap">
							<el-input type="password" maxlength="6" v-model="formObj.pay_password" :placeholder="$t('auth.register.i6password')"></el-input>
						</div>
					</el-form-item>
					<el-form-item :label="$t('auth.register.invite')" prop="source_member">
						<div class="apply-wrap">
							<el-input v-model="formObj.source_member" :placeholder="$t('auth.register.inviteuid')"></el-input>
						</div>
					</el-form-item>
					<el-form-item :label="$t('auth.register.code')" prop="captcha_code">
						<div class="apply-wrap wrap-last">
							<el-input v-model="formObj.captcha_code" :placeholder="$t('auth.register.icode')" maxlength="4"></el-input>
							<img :src="captcha.img" mode class="captcha" @click="getCode" />
						</div>
					</el-form-item>
					<el-form-item><el-button  type="primary" @click="submitForm()">{{ $t('auth.register.register') }}</el-button></el-form-item>
					<div class="xy" @click="check">
						<div class="xy-wrap">
							<div class="iconfont" :class="ischecked ? 'iconxuanze-duoxuan' : 'iconxuanze'"></div>
							<div class="content">
                                {{ $t('auth.register.readAndAgree') }}
								<b @click.stop="getAggrement">《{{ $t('auth.register.protocol') }}》</b>
							</div>
						</div>
						<div class="toLogin" @click="toLogin">{{ $t('auth.register.gotologin') }}</div>
					</div>
				</el-form>
			</div>
			<el-dialog :title="agreement.title" :visible.sync="aggrementVisible" width="60%" :before-close="aggrementClose" :lock-scroll="false" center>
				<div v-html="agreement.content" class="xyContent"></div>
			</el-dialog>
		</div>

	</div>
</template>

<script>
import { getRegisiterAggrement, register, registerConfig,registerTel,registerEmail } from '@/api/auth/register';
import {  countryFn } from '@/api/member/info';
import { captcha } from '@/api/website';
export default {
	name: 'register',
	components: {},
	data() {
		var checkPassValidata = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.registerForm.password) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		let self = this;
		var passwordValidata = function(rule, value, callback) {
			let regConfig = self.registerConfig;
			if (!value) {
				return callback(new Error('请输入密码'));
			} else {
				if (regConfig.pwd_len > 0) {
					if (value.length < regConfig.pwd_len) {
						return callback(new Error('密码长度不能小于' + regConfig.pwd_len + '位'));
					} else {
						callback();
					}
				} else {
					if (regConfig.pwd_complexity != '') {
						let passwordErrorMsg = '密码需包含',
							reg = '';
						if (regConfig.pwd_complexity.indexOf('number') != -1) {
							reg += '(?=.*?[0-9])';
							passwordErrorMsg += '数字';
						} else if (regConfig.pwd_complexity.indexOf('letter') != -1) {
							reg += '(?=.*?[a-z])';
							passwordErrorMsg += '、小写字母';
						} else if (regConfig.pwd_complexity.indexOf('upper_case') != -1) {
							reg += '(?=.*?[A-Z])';
							passwordErrorMsg += '、大写字母';
						} else if (regConfig.pwd_complexity.indexOf('symbol') != -1) {
							reg += '(?=.*?[#?!@$%^&*-])';
							passwordErrorMsg += '、特殊字符';
						} else {
							reg += '';
							passwordErrorMsg += '';
						}

						if (reg.test(value)) {
							return callback(new Error(passwordErrorMsg));
						} else {
							callback();
						}
					}
				}
			}
		};
		return {
			registerForm: {
				username: '',
				password: '',
				checkPass: '',
				code: ''
			},
			registerRules: {
				username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
				password: [
					{
						required: true,
						validator: passwordValidata,
						trigger: 'blur'
					}
				],
				checkPass: [{ required: true, validator: checkPassValidata, trigger: 'blur' }],
				code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
			},
			ischecked: false,
			agreement: '',
			aggrementVisible: false,
			captcha: {
				// 验证码
				id: '',
				img: ''
			},
			registerConfig: {},


			tabIndex: 1,
			formObj: {
				mobile: '', // 手机号
				password: '', // 密码
				nickname: '', // 姓名 
				email: '',  // 邮箱
				source_member: '', //邀请人uid
				pay_password: '', // 支付密码
				captcha_code: '', // 验证码
				phone_code: '86',
				captcha_id: '',
			},
			formRules: {
				nickname: [{
					required: true,
					message: "请输入用户名",
					trigger: "blur"
				}],
				password: [{
					required: true,
					message: "请输入登录密码",
					trigger: "blur"
				}],
				pay_password: [{
					required: true,
					message: "设置6位纯数字交易密码",
					trigger: "blur"
				}],
				source_member: [{
					required: true,
					message: "请输入邀请人ID",
					trigger: "blur"
				}],
				captcha_code: [{
					required: true,
					message: "请输入验证码",
					trigger: "blur"
				}],
			},
			showTel: false,
			countryAry: [],
		};
	},
	created() {
		this.getCode();
		this.regisiterAggrement();
		this.getRegisterConfig();
		this.getCountry();
		
	},
	computed: {
		
	},
	methods: {
		check() {
			this.ischecked = !this.ischecked;
		},
		toLogin() {
			this.$router.push('/login');
		},
		//  获取注册配置
		getRegisterConfig() {
			registerConfig()
				.then(res => {
					if (res.code >= 0) {
						this.registerConfig = res.data.value;
						if (this.registerConfig.register == '') {
							this.$message({
								message: this.$t('auth.register.platformnotstart'),
								type: 'warning',
								duration: 2000,
								onClose: () => {
									this.$router.push('/');
								}
							});
						}
					}
				})
				.catch(err => {
					console.log(err.message)
				});
		},
		// 注册
		register() {
			this.$refs.registerRef.validate(valid => {
				if (valid) {
					if (!this.ischecked) {
						return this.$message({
							message: '请先阅读协议并勾选',
							type: 'warning'
						});
					}
					var data = {
						username: this.registerForm.username.trim(),
						password: this.registerForm.password
					};
					if (this.captcha.id != '') {
						data.captcha_id = this.captcha.id;
						data.captcha_code = this.registerForm.code;
					}
					this.$store
						.dispatch('member/register_token', data)
						.then(res => {
							if (res.code >= 0) {
								this.$router.push('/member/index');
							}
						})
						.catch(err => {
							this.$message.error(err.message);
							this.getCode();
						});
				} else {
					return false;
				}
			});
		},
		aggrementClose() {
			this.aggrementVisible = false;
		},
		// 获取协议
		regisiterAggrement() {
			getRegisiterAggrement()
				.then(res => {
					if (res.code >= 0) {
						this.agreement = res.data;
					}
				})
				.catch(err => {
					console.log(err.message)
				});
		},
		getAggrement() {
			this.aggrementVisible = true;
		},
		// 获取验证码
		getCode() {
			captcha({ captcha_id: 'this.captcha.id' })
				.then(res => {
					if (res.code >= 0) {
						this.captcha = res.data;
						this.captcha.img = this.captcha.img.replace(/\r\n/g, '');
						this.formObj.captcha_id = this.captcha.id
					}
				})
				.catch(err => {
					this.$message.error(err.message);
				});
		},


		setTab(type){
			this.tabIndex = type;
			// if(type == 1){
			// 	this.formObj.mobile = '';
			// }else {
			// 	this.formObj.email = '';
			// }
		},
		getCountry(){
			countryFn().then(res=>{
				if(res.code == 0){
					this.countryAry = res.data;
				}
        this.loading = false
			})
		},
		setCountry(obj){
			this.formObj.phone_code = obj.tel;
			this.showTel = false;
		},
		submitForm(){
			this.$refs.formRef.validate(valid => {
				if(valid){
					if(this.tabIndex == 1 && !this.formObj.mobile){
						return this.$message.warning(this.$t('auth.register.imobile'))
					}
					if(this.tabIndex == 2 && !this.formObj.email){
						return this.$message.warning(this.$t('auth.register.iemail'))
					}
					let regNumber = /^\+?[1-9][0-9]*$/; // 正整数
					if(!regNumber.test(this.formObj.pay_password)){
						return this.$message.warning(this.$t('auth.register.i6password'))
					}
					if (!this.ischecked) {
						return this.$message({
							message: this.$t('auth.register.checkprotocel'),
							type: 'warning'
						});
					}
					if(this.tabIndex == 1){
						this.formObj.email = '';
						this.submitTel(this.formObj);
					}else if(this.tabIndex == 2){
						this.formObj.mobile = '';
						this.submitEmail(this.formObj);
					}
				}else {
					return false;
				}
			})
		},
		submitTel(data) {
			console.log(1111)
			registerTel(data).then((res) =>{
				if(res.code == 0){
					this.$message.success(this.$t('auth.register.registersuccess'))
					this.$store.dispatch('member/add_token',res.data.token)
					this.$router.push('/member/index');
				}else {
					this.getCode()
					this.$message({
						message: res.message,
						type: "warning"
					})
				}
			}).catch(err => {
				this.$message.error(err.message)
				this.getCode()
			})
		},
		submitEmail(data) {
			registerEmail(data).then((res) =>{
				if(res.code == 0){
					this.$message.success(this.$t('auth.register.registersuccess'))
					this.$store.dispatch('member/add_token',res.data.token)
					this.$router.push('/member/index');
				}else {
					this.getCode()
					this.$message({
						message: res.message,
						type: "warning"
					})
				}
			}).catch(err => {
				this.$message.error(err.message)
				this.getCode()
			})
		},







	}
};
</script>

<style lang="scss">
  #register-index {
    .el-tabs__active-bar,
    .el-tabs__nav-wrap::after {
      /* 清除tab标签底部横线 */
      height: 1px;
    }
		.content-register {
			.el-input__inner {
				border: none;
				height: 38px;
			}
		}
  }
</style>

<style lang="scss" scoped>
.register {
	width: 100%;
	height: 100%;
	// display: flex;
	// justify-content: center;
	// align-items: center;
	// margin: 20px 0;
}
	.box-card {
		width: 500px;
		margin: 0 auto;
		display: flex;
		background-color: #ffffff;
		padding: 0 30px 30px 30px;
		flex-direction: column;

		.register-title {
			border-bottom: 1px solid #f1f1f1;
			text-align: left;
			margin-bottom: 20px;
			font-size: 16px;
			color: $base-color;
			padding: 10px 0;
		}
		.register-account {
			width: 100%;
			text-align: center;
		}
		.code {
			width: 80%;
			text-align: left;
		}
		.el-form {
			margin: 0 30px;
			.captcha {
				vertical-align: top;
				max-width: inherit;
				max-height: 38px;
				line-height: 38px;
				cursor: pointer;
			}
		}
		.xyContent {
			height: 600px;
			overflow-y: scroll;
		}
		.xy {
			margin-left: 110px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			text-align: left;
			margin-right: 30px;
			.toLogin {
				cursor: pointer;
			}
			.xy-wrap {
				display: flex;
				align-items: center;
				font-size: $ns-font-size-base;
				cursor: pointer;
				.iconfont {
					display: flex;
					align-content: center;
                }
				.content {
                    margin-left: 3px;
					b {
						color: $base-color;
					}
				}
			}
			.iconxuanze-duoxuan {
				color: $base-color;
			}
		}
		.el-button {
			margin-top: 20px;
			background-color: $base-color;
			color: #ffffff;
			width: calc(100% - 60px);
		}
	}


	.content-register {
		width: 500px;
		margin: 0 auto;
		.header-reg {
			width: 100%;
			border-bottom: 1px solid #E8EDF5;
			.reg-tab {
				// width: 86%;
				margin: 0 auto;
				display: flex;
				align-items: center;
				.tab {
					font-size: 16px;
					color: #909399;
					margin-right: 20px;
					line-height: 40px;
				}
				.tab-act {
					color: #ff4544;
					font-weight: 500;
				}
			}
		}
		.form-box {
			padding-top: 30px;
			.apply-wrap {
				color: #FF547B;
				width: 400px;
				height: 40px;
				border: 1px solid #DCDFE6;
				border-radius: 4px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0px 15px;
				box-sizing: border-box;
				.code {
					display: flex;
					align-items: center;
					span {
						font-size: 14px;
						color: #303133;
						margin-right: 6px;
					}
				}
				.captcha {
					vertical-align: top;
					max-width: inherit;
					max-height: 38px;
					line-height: 38px;
					cursor: pointer;
				}
			}
			.wrap-last {
				padding-right: 0px;
			}
			.row-box {
        // padding-bottom: 20px;
        position: relative;
        .country-ul {
          position: absolute;
          left: 0px;
          top: 40px;
          width: 400px;
          max-height: 300px;
          overflow: auto;
          background-color: rgb(255, 255, 255);
          box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
          z-index: 11;
          .country-li {
            padding: 0px 16px;
            box-sizing: border-box;
          }
          .country-li:hover {
            background: #F7F7F7;
            .li-name {
              color: #FF547B;
            }
          }
        }
        .proxy-ul {
          .proxy-li {
            line-height: 40px;
          }
        }
      }
			.el-form {
				.el-button {
					margin-top: 20px;
					background-color: $base-color;
					color: #ffffff;
					width: calc(100% - 60px);
				}
			}
			.xy {
                width: 500px;
                margin: 0 auto;
                text-align: center;
                //margin-left: 110px;
				//display: flex;
				//justify-content: space-between;
				//align-items: center;
				text-align: left;
				//margin-right: 30px;
				.toLogin {
					cursor: pointer;
				}
				.xy-wrap {
                    //display: flex;
                    display: inline-block;
					align-items: center;
					font-size: $ns-font-size-base;
					cursor: pointer;
					.iconfont {
						display: flex;
						align-content: center;
                        float: left;
					}
					.content {
                        line-height: 29px;
						margin-left: 3px;
                        display: inline-block;
						b {
							color: $base-color;
						}
					}
				}
				.iconxuanze-duoxuan {
					color: $base-color;
				}
                .toLogin{
                    display: inline-block;
                }
			}
		}
	}

</style>
